package com.dg.river.core.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.util.List;

/**
 * Created by hy on 2018/10/16
 * Description : 检查权限工具类
 */
public class PermissionsCheckerUtils {

    private final Context mContext;

    public PermissionsCheckerUtils(Context context) {
        mContext = context.getApplicationContext();
    }

    // 判断权限集合
    public boolean lacksPermissions(String... permissions) {
        for (String permission : permissions) {
            if (lacksPermission(permission)) {
                return true;
            }
        }
        return false;
    }

    // 判断是否缺少权限
    private boolean lacksPermission(String permission) {
        return ContextCompat.checkSelfPermission(mContext, permission) ==
                PackageManager.PERMISSION_DENIED;
    }

    public interface OnRequestPermissionListener {
        // 同意权限
        void onGranted();

        // 拒绝权限
        void onReject();
    }

    /**
     * 检查通知权限
     *
     * @param activity
     * @param listener
     */
    public static void checkNotification(Activity activity, OnRequestPermissionListener listener) {
        XXPermissions.with(activity)
                .permission(Permission.NOTIFICATION_SERVICE)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (listener != null) {
                            if (allGranted) {
                                listener.onGranted();
                            } else {
                                listener.onReject();
                            }
                        }
                    }
                });
    }

    /**
     * 校验定位权限是否开启
     *
     * @param mContext
     * @return
     */
    public static boolean checkLocationPermission(Context mContext) {
        return XXPermissions.isGranted(mContext, Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION);
    }
}
